package com.tea.web.controller.system;

import com.tea.common.constant.Constants;
import com.tea.common.core.domain.AjaxResult;
import com.tea.common.core.domain.entity.SysMenu;
import com.tea.common.core.domain.entity.SysUser;
import com.tea.common.core.domain.model.LoginBody;
import com.tea.common.model.WxUser;
import com.tea.common.utils.SecurityUtils;
import com.tea.common.utils.StringUtils;
import com.tea.framework.web.service.SysLoginService;
import com.tea.framework.web.service.SysPermissionService;
import com.tea.funct.domain.TeaMember;
import com.tea.funct.service.ITeaMemberService;
import com.tea.funct.utils.util.MiniCodePosterUtil;
import com.tea.system.service.ISysMenuService;
import com.tea.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * 登录验证
 *
 * @author Sophia
 */
@Slf4j
@RestController
public class SysLoginController {

    @Autowired
    private SysLoginService loginService;
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ITeaMemberService teaMemberService;
    @Autowired
    private MiniCodePosterUtil miniCodePosterUtil;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 模拟微信登录方法
     *
     * @param code 登录信息
     * @return 结果
     */
    @PostMapping("/wxLoginTest/{code}")
    public AjaxResult wxLoginTest(@PathVariable("code") String code) {
        AjaxResult ajax = AjaxResult.success();
        String openId = "ofY4d7ZdKTpAUXXDIvA-3xE7zcq" + code;
        String sessionKey = "oN3nbEi+2itAXhCt+vsfQ==" + code;
        log.info("根据openId查询库中是否存在该用户...");
        WxUser wxUser = userService.selectWxUserByOpenId(openId);
        String password = "HqUser@2024";
        if (wxUser == null) {
            SysUser sysUser = new SysUser();
            // 用户首次授权登录
            log.info("用户首次授权登录，将该用户的openId和sessionKey保存到数据库中...");
            sysUser.setOpenId(openId);
            sysUser.setSessionKey(sessionKey);
            sysUser.setUserDesc("一扫而过, 片甲不留");
            sysUser.setNickName("百货行情");
            sysUser.setPhonenumber("15517528729");
            sysUser.setAvatar("https://img95.699pic.com/xsj/16/e1/yr.jpg%21/fh/300");
            sysUser.setSex("0");
            // 设置默认账号和密码
            sysUser.setUserName("HqUser");
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            userService.insert(sysUser);
            SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
            String format = sysUser.getUserName() + sysUser.getUserId() + sdf.format(new Date());
            sysUser.setUserName(format);
            sysUser.setNickName(sysUser.getNickName() + sysUser.getUserId());
            userService.update(sysUser);
            // 生成推荐码
            String referralCode = "BHPS" + sysUser.getUserId() + StringUtils.getRandomCode(7, 3);
            TeaMember teaMember = new TeaMember();
            teaMember.setUserId(sysUser.getUserId());
            teaMember.setReferralCode(referralCode);
            teaMember.setSuperReferralCode("");
            teaMember.setDisable("0");
            teaMember.setExtractableDays(0l); // 默认可提现天数
            teaMember.setDrawnDays(0l); // 默认已提现天数
            // TODO 需新增生成小程序推广码字段并记录在库
            // 设置小程序推广二维码
            String qrCodeFileName = miniCodePosterUtil.createMiniQrCodeByReferralCode(teaMember.getReferralCode());
            teaMember.setSmallShareQrcode(qrCodeFileName);
            // 设置海报推广二维码
            String pushPosterImage = miniCodePosterUtil.createPushPoster(teaMember.getSmallShareQrcode(), referralCode);
            teaMember.setRecommendedPoster(pushPosterImage);
            // 存储会员信息
            teaMemberService.insertTeaMember(teaMember);
            wxUser = userService.selectWxUserByOpenId(openId);
        } else {
            // 该微信用户已存在
            log.info("该微信用户已存在...直接登录！");
        }
        // 生成token令牌
        String token = loginService.wxLogin(wxUser.getUserName(), password);
        ajax.put(Constants.TOKEN, token);
        ajax.put("wxUser", wxUser);
        return ajax;
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

}
